package cn.kgc.javaweb.listener;

import cn.kgc.javaweb.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/9/13
 * SessionScopeListener
 * HttpSessionAttributeListener 监听器 监听session中值改变的过程
 */
@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {

    private HashMap<Integer,HttpSession> hashMap = new HashMap<>();
    /**
     * @param event
     */
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {

        // session 存储值的key
        String name = event.getName();
        //获取当前的会话对象
        HttpSession session = event.getSession();

        // 全局域对象
        ServletContext servletContext = session.getServletContext();

        if ("user".equals(name)){
            // session 存储值的value
            User user = (User) event.getValue();
            Integer userId = user.getId();

            //实现单点登录
            if(hashMap.containsKey(userId)){
                HttpSession httpSession = hashMap.get(userId);
                httpSession.invalidate();
            }

            hashMap.put(userId, session);
            servletContext.setAttribute("hashmap", hashMap);
        }
        System.out.println(hashMap);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("session中移除了一个值");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        System.out.println("session中替换了一个值");
    }
}
